import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
// import * as protobuf from 'protobufjs'
// import * as pako from 'pako'
import * as crypto from 'crypto'

console.warn('该项目仅学习研究，请勿用作非法用途。如果追加法律责任与本人无关')

const package_ = fs.readFileSync(path.join(__dirname, '../../package.json')).toString('utf-8')
// Custom APIs for renderer
const api = {
  md5: (str) => {
    return crypto
      .createHash('md5')
      .update(str + '')
      .digest('hex')
      .toLocaleUpperCase()
  },
  /**
   * 单位转换
   */
  bytesChange: (limit) => {
    let size = ''
    if (limit < 0.1 * 1024) {
      size = limit.toFixed(2) + 'B'
    } else if (limit < 0.1 * 1024 * 1024) {
      size = (limit / 1024).toFixed(2) + 'KB'
    } else if (limit < 0.1 * 1024 * 1024 * 1024) {
      size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
    } else {
      size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
    }

    let sizeStr = size + ''
    let index = sizeStr.indexOf('.')
    let dou = sizeStr.substring(index + 1, index + 3)
    if (dou == '00') {
      return sizeStr.substring(0, index) + sizeStr.substring(index + 3, index + 5)
    }
    return size
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
    contextBridge.exposeInMainWorld('isClient', true)
    contextBridge.exposeInMainWorld('fs', fs)
    contextBridge.exposeInMainWorld('path', path)
    contextBridge.exposeInMainWorld('os', os)
    contextBridge.exposeInMainWorld('Buffer', Buffer)
    // contextBridge.exposeInMainWorld('protobuf', protobuf)
    // contextBridge.exposeInMainWorld('pako', pako)
    contextBridge.exposeInMainWorld('package_', JSON.parse(package_))
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
  window.isClient = true
  window.fs = fs
  window.path = path
  window.os = os
  window.Buffer = Buffer
  // window.protobuf = protobuf
  // window.pako = pako
  window.package_ = JSON.parse(package_)
}
